package com.tiger.smartapp;

import java.util.ArrayList;
import java.util.List;

import net.youmi.android.AdListener;
import net.youmi.android.AdManager;
import net.youmi.android.AdView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class MainActivity extends BaseActivity implements AdListener {
//	static {
//		// 应用Id 应用密码 广告请求间隔(s) 测试模式 应用版本号
//		AdManager.init("8f7a2c6a9d881a58", "1bc7f6051671cfcb", 31, false, 2.1);
//	}
	private Button uninstall,install;
	private ListView applist;
	private MyAdapter adapter;
	private ProgressDialog pd_downloading;
	private ArrayList<PInfo> mData;   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.installedlist);
        
        applist= (ListView)this.findViewById(R.id.app_list);
		adapter = new MyAdapter(this);  
		pd_downloading=new ProgressDialog(MainActivity.this);
		pd_downloading.setMessage("正在读取应用程序信息");
		pd_downloading.show();
        uninstall=(Button)this.findViewById(R.id.xiezai);
        install=(Button)this.findViewById(R.id.anzhuang);
        install.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				MainActivity.this.startActivity(new Intent(MainActivity.this,ApklistActivity.class));
			}
        });
        uninstall.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				adapter.notifyDataSetChanged();
			}
        });
       
        applist.setAdapter(adapter); 
        applist.setOnItemClickListener(mLeftListOnItemClick);   
        
		new Thread(new LoadThread()).start();
		
//		CommonUtil.setAdView(this, this);
    }
    AdapterView.OnItemClickListener mLeftListOnItemClick = new AdapterView.OnItemClickListener() {   
        public void onItemClick(AdapterView<?> arg0, View view, int arg2,long arg3) {   
        	ApkHolder holder = (ApkHolder) view.getTag();  
        	if(holder!=null){
        		unstallApk(holder.apkPath);
        	}
        }   
	};
    class PInfo {
		private String appname = "";
		private String pname = "";
		private String versionName = "";
		private int versionCode = 0;
		private Drawable icon;
	}
    class ApkHolder{
		ImageView apkIcon;
		TextView apkName;
		String apkPath;
	}
    private class MyAdapter extends BaseAdapter {   
		 
        private LayoutInflater mInflater;   
        public MyAdapter(Context context) {   
            this.mInflater = LayoutInflater.from(context);   
        }   
        public int getCount() {   
            // TODO Auto-generated method stub   
        	if(mData==null)
        		return 0;
            return mData.size();   
        }   
        public Object getItem(int arg0) {   
            // TODO Auto-generated method stub   
        	if(mData==null)
        		return null;
            return mData.get(arg0);   
        }   
        public long getItemId(int arg0) {   
            // TODO Auto-generated method stub   
            return arg0;   
        }   
		public View getView(int position, View convertView, ViewGroup parent) {   
			ApkHolder holder = null;   
            if (convertView == null) {   
                holder = new ApkHolder();   
                convertView = mInflater.inflate(R.layout.installeditem, null);   
                holder.apkName = (TextView) convertView.findViewById(R.id.apkName);   
                holder.apkIcon = (ImageView) convertView.findViewById(R.id.apkIcon);   
               
            } else {   
                holder = (ApkHolder) convertView.getTag();   
            }   
               
            if(mData!=null){
            	Log.i("MMALL", mData.get(position).appname);
            holder.apkName.setText((String) mData.get(position).appname);   
            holder.apkIcon.setImageDrawable(mData.get(position).icon);    
            holder.apkPath=mData.get(position).pname;
            }
            convertView.setTag(holder);          
            return convertView;   
        }   
    }   
    private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
		ArrayList<PInfo> res = new ArrayList<PInfo>();
		List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			PInfo newInfo = new PInfo();
			newInfo.appname = p.applicationInfo.loadLabel(getPackageManager())
					.toString();
			newInfo.pname = p.packageName;
			newInfo.versionName = p.versionName;
			newInfo.versionCode = p.versionCode;
			newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
			if (!p.applicationInfo.sourceDir.startsWith("/system/app")) {
				res.add(newInfo);
				continue;
			}

			if (getSysPackages) {
				res.add(newInfo);
				continue;
			}
//			Log.i(CommonUtil.TAG, newInfo.appname);
		}
		return res;
	}

	/**
	 * 卸载
	 * @param packageName
	 */
	public void unstallApk(String packageName){
		try {
			final String packageName_=packageName;
			new AlertDialog.Builder(this).setTitle("提示").setMessage("确认卸载该应用程序吗?")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					CommonUtil.uninstall(packageName_, MainActivity.this);
				}
			}).setNegativeButton("取消",  new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					arg0.dismiss();
				}
				
			}).show();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CommonUtil.status.DO:
		        if(adapter!=null){
		        	Log.i("MMALL", "mData SIZE:"+mData.size());
		        	adapter.notifyDataSetChanged();
		        }
				break;
			}
		}
	};
    private class LoadThread implements Runnable{

		@Override
		public void run() {
			mData=getInstalledApps(false);
	        if(mData!=null&&mData.size()>0){
	        	handler.sendEmptyMessage(CommonUtil.status.DO);
	        	if(pd_downloading!=null){
					pd_downloading.dismiss();
				}
	        }
		}
		
	}
	@Override
	public void onConnectFailed(AdView arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onReceiveAd(AdView arg0) {
		// TODO Auto-generated method stub
		
	};
}